package com.pan.code.impl;

import com.pan.code.VerificationCode;
import com.pan.entity.Base64Result;
import com.pan.picture.Picture;
import com.pan.picture.impl.CodePicture;
import com.pan.utils.RandomCode;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;


public class StringVerificationCode implements VerificationCode {

    private Picture picture;

    public static final int DEFAULT_LENGTH = 5;


    public StringVerificationCode(){
        picture = new CodePicture();
    }

    @Override
    public Base64Result getBase64(){return this.getBase64(DEFAULT_LENGTH);};
    public Base64Result getBase64(int len){
        if (len<=0) throw new RuntimeException("参数不能 len<=0");
        char[] chars = RandomCode.getChars(len);
        picture.reset(String.valueOf(chars));
        picture.interfere();
        BufferedImage bufferedImage = picture.getImage();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        try {
            ImageIO.write(bufferedImage, "jpg", baos);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();//转换成字节
        Base64.Encoder encoder = Base64.getEncoder();
        String jpg_base64 = encoder.encodeToString(bytes).trim();//转换成base64串
        jpg_base64 = jpg_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        String base64 = "data:image/jpg;base64," + jpg_base64;
        return new Base64Result(String.valueOf(chars),base64);
    }


    public String get(int len,String outPicturePath,String pictureName){
        if (len<=0) throw new RuntimeException("参数不能 len<=0");
        char[] chars = RandomCode.getChars(len);
        picture.reset(String.valueOf(chars));
        picture.interfere();
        BufferedImage image = picture.getImage();
        File outFile  = new File(outPicturePath+"\\"+pictureName+".jpg");
        if (outFile.exists()) throw new RuntimeException("该图片已存在");
        try {
            outFile.createNewFile();
            ImageIO.write(image,"jpg",outFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return String.valueOf(chars);
    }


    public String get(String pictureName){
        String dirPath = System.getProperty("user.dir")+"\\result";
        File file = new File(dirPath);
        if (!file.exists())file.mkdir();
        return this.get(dirPath,pictureName);
    }

    @Override
    public String get(String filePath,String fileName){
        return this.get(DEFAULT_LENGTH,filePath,fileName);
    }

    @Override
    public void close() {
        picture.close();
    }

}
